package com.koron.order.cockpitStats.business.service.Impl;

import com.koron.bean.base.Response;
import com.koron.bean.system.org.OrgBean;
import com.koron.common.core.business.system.feign.SystemFeignService;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.util.StringUtils;
import com.koron.order.cockpitStats.business.bean.dto.PlanStatsDto;
import com.koron.order.cockpitStats.business.bean.query.DefectStatsQuery;
import com.koron.order.cockpitStats.business.bean.vo.DefectStatsGatherVo;
import com.koron.order.cockpitStats.business.bean.vo.DefectStatsVo;
import com.koron.order.cockpitStats.business.bean.vo.OrderPassRateGatherVo;
import com.koron.order.cockpitStats.business.bean.vo.PlanStatsGatherVo;
import com.koron.order.cockpitStats.business.mapper.StatsMapper;
import com.koron.order.cockpitStats.business.service.StatsService;
import com.koron.order.common.util.DateUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.TaskAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName StatsServiceImpl
 * @description
 * @Author zhouj
 * @Date 2022/5/24 14:51
 */
@Service
public class StatsServiceImpl implements StatsService {

    @Autowired
    SystemFeignService systemFeignService;

    @TaskAnnotation("queryDefectStats")
    @Override
    public DefectStatsGatherVo queryDefectStats(SessionFactory factory, DefectStatsQuery defectStatsQuery) {
        StatsMapper mapper = factory.getMapper(StatsMapper.class);

        //1.1 构建返回对象
        DefectStatsGatherVo defectStatsGatherVo = new DefectStatsGatherVo();

        //1.2 通过feign调用 管理类型组织,传入上级组织id
        OrgBean orgBean = new OrgBean();
        orgBean.setType("management");
        orgBean.setLevelPath(defectStatsQuery.getParentOrgId());
        orgBean.setAppCode(ThreadLocalContext.get().getCurrDs());
        Response<List<OrgBean>> response = systemFeignService.queryNextOrgList(orgBean);
        List<OrgBean> orgBeanList = response.getData();
        if (CollectionUtils.isEmpty(orgBeanList)) {
            return defectStatsGatherVo;
        }
        //排除自己
        Iterator<OrgBean> iterator = orgBeanList.iterator();
        while (iterator.hasNext()) {
            if (iterator.next().getId().equals(defectStatsQuery.getParentOrgId())) {
                iterator.remove();
            }
        }

        Map<String, String> orgIdMap = orgBeanList.stream().collect(Collectors.toMap(OrgBean::getId, OrgBean::getParent));

        List<OrgBean> parentList = new ArrayList<>();

        //1.3 所有应该统计的组织id
        List<String> orgIds = orgBeanList.stream().map(OrgBean::getId).collect(Collectors.toList());
        defectStatsQuery.setOrgIds(orgIds);

        //展示的一级列表
        for (OrgBean bean : orgBeanList) {
            String parentId = queryMaxParentId(orgIdMap, bean.getId());
            if (StringUtils.isEmpty(parentId)) {
                continue;
            }
            if (parentId.equals(bean.getId())) {
                parentList.add(bean);
            }
        }

        //1.4 处理时间范围,默认取当前月
        if (defectStatsQuery.getMonth() == null) {
            defectStatsQuery.setMonth(new Date());
        }
        defectStatsQuery.setMonthStart(DateUtils.getMonthStart(defectStatsQuery.getMonth()));
        defectStatsQuery.setMonthEnd(DateUtils.getMonthEnd(defectStatsQuery.getMonth()));

        //2.1 实际查询数据列表
        List<DefectStatsVo> defectStatsVoList = mapper.queryDefectStats(defectStatsQuery);
        if (CollectionUtils.isEmpty(defectStatsVoList)) {
            return defectStatsGatherVo;
        }

        //2.2 需要对数据进行分组,本级及下级统计在一起(部门及单位)
        Map<String, List<DefectStatsVo>> defectStatsOrgMap = new HashMap<>();
        for (DefectStatsVo defectStatsVo : defectStatsVoList) {
            String orgId = defectStatsVo.getOrgId();
            String parentId = queryMaxParentId(orgIdMap, orgId);
            if (StringUtils.isEmpty(parentId)) {
                continue;
            }
            List<DefectStatsVo> defectStatsVos = defectStatsOrgMap.getOrDefault(parentId, new ArrayList<>());
            defectStatsVos.add(defectStatsVo);
            defectStatsOrgMap.put(parentId, defectStatsVos);
        }

        //3.1 进一步对分组后的数据进行部门数据统计
        List<DefectStatsVo> defectStatsVoArrayList = new ArrayList<>();
        for (OrgBean bean : parentList) {
            DefectStatsVo defectStatsVo = new DefectStatsVo();
            List<DefectStatsVo> defectStatsVos = defectStatsOrgMap.get(bean.getId());
            defectStatsVo.setOrgId(bean.getId());
            defectStatsVo.setOrgName(bean.getName());
            if (CollectionUtils.isNotEmpty(defectStatsVos)) {
                defectStatsVo.setRescue(defectStatsVos.stream().mapToInt(DefectStatsVo::getRescue).sum());
                defectStatsVo.setOneclass(defectStatsVos.stream().mapToInt(DefectStatsVo::getOneclass).sum());
                defectStatsVo.setTwoclass(defectStatsVos.stream().mapToInt(DefectStatsVo::getTwoclass).sum());
                defectStatsVo.setThreeclass(defectStatsVos.stream().mapToInt(DefectStatsVo::getThreeclass).sum());
                defectStatsVo.setUrgent_line(defectStatsVos.stream().mapToInt(DefectStatsVo::getUrgent_line).sum());
                defectStatsVo.setMajor_line(defectStatsVos.stream().mapToInt(DefectStatsVo::getMajor_line).sum());
                defectStatsVo.setCommonly_line(defectStatsVos.stream().mapToInt(DefectStatsVo::getCommonly_line).sum());
                defectStatsVo.setIsFinishOnTime(defectStatsVos.stream().mapToInt(DefectStatsVo::getIsFinishOnTime).sum());
                defectStatsVo.setIsFinish(defectStatsVos.stream().mapToInt(DefectStatsVo::getIsFinish).sum());
                defectStatsVo.setTotal(defectStatsVos.stream().mapToInt(DefectStatsVo::getTotal).sum());
            }
            defectStatsVoArrayList.add(defectStatsVo);
        }
        defectStatsGatherVo.setDefectStatsVoList(defectStatsVoArrayList);
        int notArchived = staNotFinishTotal(mapper, parentList, orgIdMap, defectStatsQuery);
        defectStatsGatherVo.setNotArchived(notArchived);
        return defectStatsGatherVo;
    }

    private int staNotFinishTotal(StatsMapper mapper, List<OrgBean> parentList, Map<String, String> orgIdMap, DefectStatsQuery defectStatsQuery) {
        Date date = defectStatsQuery.getMonthEnd();
        LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate firstDayOfYear = localDate.with(TemporalAdjusters.firstDayOfYear());
        LocalDate lastDayOfPreviousMonth = localDate.minusMonths(1).with(TemporalAdjusters.lastDayOfMonth());

        Date monthStart = Date.from(firstDayOfYear.atStartOfDay(ZoneId.systemDefault()).toInstant());
        Date monthEnd = Date.from(lastDayOfPreviousMonth.atStartOfDay(ZoneId.systemDefault()).toInstant());
        defectStatsQuery.setMonthStart(monthStart);
        defectStatsQuery.setMonthEnd(monthEnd);
        List<DefectStatsVo> defectStatsVoList = mapper.queryDefectStats(defectStatsQuery);
        //2.2 需要对数据进行分组,本级及下级统计在一起(部门及单位)
        Map<String, List<DefectStatsVo>> defectStatsOrgMap = new HashMap<>();
        for (DefectStatsVo defectStatsVo : defectStatsVoList) {
            String orgId = defectStatsVo.getOrgId();
            String parentId = queryMaxParentId(orgIdMap, orgId);
            if (StringUtils.isEmpty(parentId)) {
                continue;
            }
            List<DefectStatsVo> defectStatsVos = defectStatsOrgMap.getOrDefault(parentId, new ArrayList<>());
            defectStatsVos.add(defectStatsVo);
            defectStatsOrgMap.put(parentId, defectStatsVos);
        }

        //3.1 进一步对分组后的数据进行部门数据统计
        List<DefectStatsVo> defectStatsVoArrayList = new ArrayList<>();

        for (OrgBean bean : parentList) {
            DefectStatsVo defectStatsVo = new DefectStatsVo();
            List<DefectStatsVo> defectStatsVos = defectStatsOrgMap.get(bean.getId());
            defectStatsVo.setOrgId(bean.getId());
            defectStatsVo.setOrgName(bean.getName());
            if (CollectionUtils.isNotEmpty(defectStatsVos)) {
                defectStatsVo.setRescue(defectStatsVos.stream().mapToInt(DefectStatsVo::getRescue).sum());
                defectStatsVo.setOneclass(defectStatsVos.stream().mapToInt(DefectStatsVo::getOneclass).sum());
                defectStatsVo.setTwoclass(defectStatsVos.stream().mapToInt(DefectStatsVo::getTwoclass).sum());
                defectStatsVo.setThreeclass(defectStatsVos.stream().mapToInt(DefectStatsVo::getThreeclass).sum());
                defectStatsVo.setUrgent_line(defectStatsVos.stream().mapToInt(DefectStatsVo::getUrgent_line).sum());
                defectStatsVo.setMajor_line(defectStatsVos.stream().mapToInt(DefectStatsVo::getMajor_line).sum());
                defectStatsVo.setCommonly_line(defectStatsVos.stream().mapToInt(DefectStatsVo::getCommonly_line).sum());
                defectStatsVo.setIsFinishOnTime(defectStatsVos.stream().mapToInt(DefectStatsVo::getIsFinishOnTime).sum());
                defectStatsVo.setIsFinish(defectStatsVos.stream().mapToInt(DefectStatsVo::getIsFinish).sum());
                defectStatsVo.setTotal(defectStatsVos.stream().mapToInt(DefectStatsVo::getTotal).sum());
            }
            defectStatsVoArrayList.add(defectStatsVo);
        }

        int notFinish = defectStatsVoArrayList.stream().map(DefectStatsVo::getNotFinish).collect(Collectors.summingInt(Integer::intValue));
        return notFinish;
    }

    @Override
    @TaskAnnotation("queryPlanStats")
    public PlanStatsGatherVo queryPlanStats(SessionFactory factory, DefectStatsQuery defectStatsQuery) {

        StatsMapper mapper = factory.getMapper(StatsMapper.class);

        //1.1 构建返回对象
        PlanStatsGatherVo planStatsGatherVo = new PlanStatsGatherVo();
        //1.2 设置查询条件
        defectStatsQuery.setMonthStart(DateUtils.getMonthStart(defectStatsQuery.getMonth()));
        defectStatsQuery.setMonthEnd(DateUtils.getMonthEnd(defectStatsQuery.getMonth()));
        defectStatsQuery.setYearStart(DateUtils.getYearStart(defectStatsQuery.getYear()));
        defectStatsQuery.setYearEnd(DateUtils.getYearEnd(defectStatsQuery.getYear()));
        List<PlanStatsDto> planStatsDtos = mapper.queryPlanStats(defectStatsQuery);

        //2.1 处理返回结果
        if (CollectionUtils.isNotEmpty(planStatsDtos)) {
            for (PlanStatsDto planStatsDto : planStatsDtos) {
                String jobType = planStatsDto.getJobType();
                switch (jobType) {
                    case "overhaul":
                        //2.2 查询大修计划的完成数和计划的总数
                        planStatsGatherVo.setOverhaulDone(planStatsDto.getDone());
                        planStatsGatherVo.setOverhaulTotal(planStatsDto.getTotal());
                        break;
                    case "repair":
                        //2.3 查询计划检修计划的完成数和计划的总数
                        planStatsGatherVo.setRepairDone(planStatsDto.getDone());
                        planStatsGatherVo.setRepairTotal(planStatsDto.getTotal());
                        break;
                    case "experiment":
                        //2.4 查询试验计划的完成数和计划的总数
                        planStatsGatherVo.setExperimentDone(planStatsDto.getDone());
                        planStatsGatherVo.setExperimentTotal(planStatsDto.getTotal());
                        break;
                    default:
                        break;
                }
            }
        }
        return planStatsGatherVo;
    }

    @Override
    @TaskAnnotation("queryOrderPassRateStats")
    public List<OrderPassRateGatherVo> queryOrderPassRateStats(SessionFactory factory, DefectStatsQuery defectStatsQuery) {

        StatsMapper mapper = factory.getMapper(StatsMapper.class);

        //1.1 返回对象
        List<OrderPassRateGatherVo> orderPassRateGatherVoList = new ArrayList<>();

        //1.2 通过feign调用 管理类型组织,传入上级组织id
        OrgBean orgBean = new OrgBean();
        orgBean.setType("management");
        orgBean.setLevelPath(defectStatsQuery.getParentOrgId());
        orgBean.setAppCode(ThreadLocalContext.get().getCurrDs());
        Response<List<OrgBean>> response = systemFeignService.queryNextOrgList(orgBean);
        List<OrgBean> orgBeanList = response.getData();
        if (CollectionUtils.isEmpty(orgBeanList)) {
            return orderPassRateGatherVoList;
        }
        Iterator<OrgBean> iterator = orgBeanList.iterator();
        while (iterator.hasNext()) {
            if (iterator.next().getId().equals(defectStatsQuery.getParentOrgId())) {
                iterator.remove();
            }
        }

        Map<String, String> orgIdMap = orgBeanList.stream().collect(Collectors.toMap(OrgBean::getId, OrgBean::getParent));

        List<OrgBean> parentList = new ArrayList<>();

        //展示的一级列表
        for (OrgBean bean : orgBeanList) {
            String parentId = queryMaxParentId(orgIdMap, bean.getId());
            if (StringUtils.isEmpty(parentId)) {
                continue;
            }
            if (parentId.equals(bean.getId())) {
                parentList.add(bean);
            }
        }

        //1.4 所有应该统计的组织id
        List<String> orgIds = orgBeanList.stream().map(OrgBean::getId).collect(Collectors.toList());

        //1.5 处理时间范围,默认取当前年
        defectStatsQuery.setYearStart(DateUtils.getYearStart(defectStatsQuery.getYear()));
        defectStatsQuery.setYearEnd(DateUtils.getYearEnd(defectStatsQuery.getYear()));

        //2.1 引入条件后实际查询sql
        defectStatsQuery.setOrgIds(orgIds);
        List<OrderPassRateGatherVo> orderPassRateGatherVos = mapper.queryOrderPassRateStats(defectStatsQuery);
        Map<String, List<OrderPassRateGatherVo>> passRateGatherVoHashMap = new HashMap<>();

        //2.2 结果集进行部门分类
        if (CollectionUtils.isNotEmpty(orderPassRateGatherVos)) {
            for (OrderPassRateGatherVo orderPassRateGatherVo : orderPassRateGatherVos) {
                String orgId = orderPassRateGatherVo.getOrgId();
                String parentId = queryMaxParentId(orgIdMap, orgId);
                if (StringUtils.isEmpty(parentId)) {
                    continue;
                }
                List<OrderPassRateGatherVo> passRateGatherVos = passRateGatherVoHashMap.getOrDefault(orgId, new ArrayList<>());
                passRateGatherVos.add(orderPassRateGatherVo);
                passRateGatherVoHashMap.put(parentId, passRateGatherVos);
            }
        }

        //3.1 组建返回对象,汇总部门统计信息
        List<OrderPassRateGatherVo> orderPassRateGatherVoArrayList = new ArrayList<>();
        for (OrgBean bean : parentList) {
            OrderPassRateGatherVo orderPassRateGatherVo = new OrderPassRateGatherVo();
            orderPassRateGatherVo.setOrgId(bean.getId());
            orderPassRateGatherVo.setOrgName(bean.getName());
            List<OrderPassRateGatherVo> orderPassRateGatherVos1 = passRateGatherVoHashMap.get(bean.getId());
            if (CollectionUtils.isNotEmpty(orderPassRateGatherVos1)) {
                orderPassRateGatherVo.setTotal(orderPassRateGatherVos1.stream().mapToInt(OrderPassRateGatherVo::getTotal).sum());
                orderPassRateGatherVo.setPassNum(orderPassRateGatherVos1.stream().mapToInt(OrderPassRateGatherVo::getPassNum).sum());
            }
            orderPassRateGatherVoArrayList.add(orderPassRateGatherVo);
        }
        return orderPassRateGatherVoArrayList;
    }

    private String queryMaxParentId(Map<String, String> orgIdMap, String id) {
        String parentId = null;
        do {
            parentId = orgIdMap.get(id);
            if (StringUtils.isNotEmpty(parentId) && StringUtils.isNotEmpty(orgIdMap.get(parentId))) {
                id = parentId;
            }
        } while (StringUtils.isNotEmpty(parentId) && StringUtils.isNotEmpty(orgIdMap.get(parentId)));
        return id;
    }

}
